from django.views import View

from Venue.models import Venue, Goods, GoodsType
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequired


class GoodsView(View):
    """ 商品信息 """

    def get(self, request):
        """ 查询 """
        venue = Venue.objects.get(id=1)
        goods = Goods.objects.filter(venue=venue)
        lists = []
        for good in goods:
            lists.append(good.Info())
        return Res.Json(Res.OK, result=lists)

    @LoginRequired.Venue
    @Req.getJson
    def post(self, request):
        """ 添加 """
        name = request.json_dict.get("name")
        typeId = request.json_dict.get("typeId")
        price = request.json_dict.get("price")
        detail = request.json_dict.get("detail")

        venue = request.user.venue
        goodsType = GoodsType.objects.filter(venue=venue, id=typeId).first()
        if not goodsType:
            return Res.Json(Res.ParamErr)

        goods = Goods.create(venue=venue, name=name, type=goodsType, price=price, detail=detail)
        return Res.Json(Res.OK, result=goods.Info())

    @LoginRequired.Venue
    @Req.getJson
    def put(self, request):
        """ 修改 """
        id = request.json_dict.get("id")
        name = request.json_dict.get("name")
        typeId = request.json_dict.get("typeId")
        price = request.json_dict.get("price")
        detail = request.json_dict.get("detail")

        venue = request.user.venue

        goods = Goods.objects.filter(venue=venue, id=id).first()
        if not goods:
            return Res.Json(Res.ParamErr)

        if name:
            goods.name = name
        if typeId:
            goodsType = GoodsType.objects.filter(venue=venue, id=typeId).first()
            if not goodsType:
                return Res.Json(Res.ParamErr)
            goods.type = goodsType
        if price:
            goods.price = price
        if detail:
            goods.detail = detail
        goods.save()
        return Res.Json(Res.OK, result=goods.Info())

    @LoginRequired.Venue
    @Req.getJson
    def delete(self, request):
        """ 删除 """
        id = request.json_dict.get("id")

        venue = request.user.venue

        goods = Goods.objects.filter(venue=venue, id=id).first()
        if not goods:
            return Res.Json(Res.ParamErr)

        goods.delete()
        return Res.Json(Res.OK)
